package com.shhic.hhplt.server.bkgrdui;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import com.shhic.hhplt.server.biz.*;
import com.shhic.hhplt.server.exceptions.PatternMismatchException;
import com.shhic.hhplt.server.service.IBoxNumberService;
import com.shhic.hhplt.server.service.IDashboardService;
import com.shhic.hhplt.server.service.ITestComplexQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shhic.hhplt.server.model.BoxNumber;

/**
 * 后台箱号管理门面
 * @author 刘琪
 *
 */
@Controller
@RequestMapping("/bkgrd")  
public class BoxNumberUiController {
	@Resource
	IBoxNumberService bnService;
	@Autowired
	ITestComplexQueryService tcxqService;
	@Resource IBoxNumberMaintaince boxNumberMaintaince;
	@Autowired
	IDashboardService dashboardService;
	
	/**
	 * 保存或更新箱号
	 * @param bn 箱子参数
	 * @return
	 */
	@RequestMapping(value = "/saveOrUpdateBoxNumber.do", method = RequestMethod.POST,produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String saveOrUpdateBoxNumber(BoxNumber bn){
		if(bn.getNowCode()==null&& bn.getScheme()==null&&bn.getCodeName()==null &&
				bn.getQuantity()==null){
			return "未输入正确参数";
		}
		String nowCode=bn.getNowCode();
		if(nowCode.length()<4||!nowCode.substring(nowCode.length()-4).matches("^\\d{4}$")){
			return "起始箱号编码输入错误，箱号为4位10进制数字";
		}
		/*int startCode=Integer.parseInt(nowCode.substring(nowCode.length()-4));
		if (boxNumberDao.getBoxNumber(bn.getCodeName())==null&&startCode!=0&&startCode%bn.getQuantity()!=0){
			return "起始箱号应该为0000,或者每箱数量的倍数";
		}*/
		try {
			boxNumberMaintaince.updateBoxNumber(bn);
		} catch (PatternMismatchException e) {
			return "起始箱号编码与模式不匹配";
		}
		bnService.insertOrUpdateBoxNumber(bn);
		return "箱号编码保存成功";
	}
	
	/**
	 * 删除箱号
	 * @return
	 */
	@RequestMapping(value = "/deleteBoxNumber.do", method = RequestMethod.GET,produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String deleteBoxNumber(@RequestParam String codeName){
		bnService.deleteBoxNumber(codeName);
		boxNumberMaintaince.notifyDeletion(codeName);
		return "箱号删除成功";
	}
	
	/**
	 * 获取全部箱号编码
	 * @return
	 */
	@RequestMapping(value = "/getAllBoxNumber.do", method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Set<BoxNumber> getAllBoxNumber(){
		return bnService.getAllBoxNumber();
	}
}
